package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.dto.ExcelDictDTO;
import com.atguigu.srb.core.mapper.DictMapper;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@NoArgsConstructor //无参构造函数
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private List<ExcelDictDTO> list = new ArrayList<>();

    private DictMapper dictMapper;

    public ExcelDictDTOListener(DictMapper dictMapper){
        this.dictMapper=dictMapper;
    }

    /**
     * 每隔10条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private final static int BATCH_COUNT = 10;

    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        log.info("解析到一条数据：{}", excelDictDTO);
        list.add(excelDictDTO);
        if(list.size()>=BATCH_COUNT){
            batchInsert();
            // 存储完成清理 list
            list.clear();
        }


    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        batchInsert();
        log.info("所有数据解析完成！");
    }

    private void batchInsert() {

        log.info("{}条数据被存储到数据库",list.size());
        //调用mapper层的batchSave()方法
        dictMapper.insertBatch(list);
        log.info("存储数据库成功！");
    }

}
